package com.humanres.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.GlideUtil;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.HttpClient;
import com.ciko.code.http.HttpResponseListener;
import com.ciko.code.http.Req.IsReadDocumentFileReq;
import com.ciko.code.http.Req.QryKnowledgeDocumentListEty;
import com.ciko.code.utils.ScreenUtil;
import com.ciko.code.utils.ToastUtils;
import com.ciko.code.utils.Util;
import com.ciko.code.views.photoview.HackyViewPager;
import com.ciko.code.views.photoview.PhotoViewAttacher;
import com.mywork.R;
import com.ui.dialog.CustomDialog;

/**
 * 政企书屋
 * 云阅读页面
 */
public class CloudReadActivity extends Activity
        implements OnClickListener, PhotoViewAttacher.OnViewTapListener, HttpResponseListener {
    private boolean showInfo = true;
    private ImageView ivTitleBack;
    private TextView tvTitle, tvName;

    private View topLayout, bottomLayout;
    private HackyViewPager viewPager;
    private SparseArray<View> views;
    private PhotoViewAttacher attacher;
    private Context context;

    private QryKnowledgeDocumentListEty qryKnowledgeDocumentListEty;
    private String mTitle;
    private Button btn_sign_read;
    //签读状态
    private boolean mSignState = true;
    private String isDocumentFile;
    private int item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏状态栏
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        //		WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.cloudread);
        context = this;
        if (getIntent().hasExtra("QryKnowledgeDocumentListEty")) {
            qryKnowledgeDocumentListEty = (QryKnowledgeDocumentListEty) getIntent().getSerializableExtra("QryKnowledgeDocumentListEty");
            mTitle = qryKnowledgeDocumentListEty.getTitle();
        } else {
            finish();
        }
        if (getIntent().hasExtra("isDocumentFile")) {
            isDocumentFile = getIntent().getStringExtra("isDocumentFile");
            item = getIntent().getIntExtra("item", -1);
        } else {
            finish();
        }
        ScreenUtil.GetInfo(context);

        findViews();
        setListeners();
        initData();
        initAnimation();
        String isRead = qryKnowledgeDocumentListEty.getIsRead();
        if ("y".equals(isDocumentFile)) {
            if ("n".equals(isRead)) {
                new CustomDialog.Builder(this)
                        .setMessage("阅读完公文，别忘记点击右上角的“签读”按钮哟")
                        .setPositiveButton("知道啦", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            } else if ("y".equals(isRead)) {
                btn_sign_read.setText("已签读");
                btn_sign_read.setBackgroundResource(R.drawable.rect_gray);
                mSignState = false;
            }
        } else {//非公文
            btn_sign_read.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != attacher) attacher.cleanup();
    }

    @Override
    public void onRequestStart(String tag) {

    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
        ToastUtils.showShort("签读成功");
        btn_sign_read.setText("已签读");
        btn_sign_read.setBackgroundResource(R.drawable.rect_gray);
        mSignState = false;
        Intent intent = new Intent();
        intent.putExtra("item", item);
        setResult(RESULT_OK, intent);
    }

    @Override
    public void onResponseFail(String tag, int resultCode) {
        ToastUtils.showShort(tag);
        btn_sign_read.setText("已签读");
        btn_sign_read.setBackgroundResource(R.drawable.rect_gray);
        mSignState = false;
//        switch (resultCode) {
//            case 5001:
//                ToastUtils.showShort("签读失败");
//                break;
//            case 5002:
//                ToastUtils.showShort("公文不存在");
//                break;
//            case 5003:
//                ToastUtils.showShort("公文已签读");
//                break;
//        }
    }

    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return qryKnowledgeDocumentListEty.getPages();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = views.get(position);
            if (view == null) {
                view = LayoutInflater.from(container.getContext()).inflate(R.layout.cloudread_item, container, false);
                final ImageView img = (ImageView) view.findViewById(R.id.cloudread_item_img);
                final ImageView ivLoading = (ImageView) view.findViewById(R.id.cloudread_item_loading_img);
                final View failLayout = view.findViewById(R.id.cloudread_item_fail_layout);
                final String url = appendImageUrl(qryKnowledgeDocumentListEty.getPdfUrl(), position + 1);
                attacher = new PhotoViewAttacher(img);
                attacher.setOnViewTapListener(CloudReadActivity.this);
                failLayout.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        loading(img, ivLoading, failLayout, url, attacher);
                    }
                });
                loading(img, ivLoading, failLayout, url, attacher);
                views.put(position, view);
            }
            if (view.getParent() != null) {
                container.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    private void loading(final ImageView img, final ImageView loading, final View fail, final String url, final PhotoViewAttacher attacher) {
        fail.setVisibility(View.GONE);
        loading.setVisibility(View.VISIBLE);
        final AnimationDrawable drawable = (AnimationDrawable) loading.getBackground();
        drawable.start();
        img.setVisibility(View.VISIBLE);
        GlideUtil.load(context, url, img, new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                Util.showToast(context, "加载失败");
                img.setVisibility(View.GONE);
                loading.setVisibility(View.GONE);
                fail.setVisibility(View.VISIBLE);
                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                drawable.stop();
                loading.setVisibility(View.GONE);
                attacher.update();
                return false;
            }
        });
    }

    private class PagerChangeListener implements OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            //			System.out.println("ViewPager onPageSelected-->"+arg0);
            final ImageView img = (ImageView) views.get(arg0).findViewById(R.id.cloudread_item_img);
            img.setScaleType(ScaleType.FIT_XY);
            PhotoViewAttacher attacher = new PhotoViewAttacher(img);
            attacher.setOnViewTapListener(CloudReadActivity.this);
            attacher.update();

            tvTitle.setText(getTitle(++arg0, qryKnowledgeDocumentListEty.getPages()));
            showSign(arg0);
            attacher.update();
        }
    }

    private String getTitle(int position, int pages) {
        return String.valueOf(position) + "/" + pages + "页";
    }

    private String appendImageUrl(String url, int page) {
        StringBuilder sb = new StringBuilder(url);
        sb.append("?c=1&w=");
        final int dpi = ScreenUtil.densityDpi;
        int width = ScreenUtil.screenWidth > 1080 ? ScreenUtil.screenWidth : ScreenUtil.screenWidth * 2;
        System.out.println("当前屏幕密度：" + dpi);
        System.out.println("当前屏幕宽度：" + width);
        sb.append(width);
        sb.append("&h=");
        final int height = ScreenUtil.screenHeight > 1920 ? ScreenUtil.screenHeight : ScreenUtil.screenHeight * 2;
        System.out.println("当前屏幕高度：" + height);
        sb.append(height);
        sb.append("&p=");
        sb.append(page);
        return sb.toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initData() {
        views = new SparseArray<>();

        showInfo = true;
        tvTitle.setText(getTitle(1, qryKnowledgeDocumentListEty.getPages()));
        showSign(1);
        tvName.setText(mTitle);
        viewPager.addOnPageChangeListener(new PagerChangeListener());
        MyPagerAdapter pagerAdapter = new MyPagerAdapter();
        viewPager.setAdapter(pagerAdapter);
    }

    private void findViews() {
        ivTitleBack = (ImageView) findViewById(R.id.cloudread_title_back);
        tvTitle = (TextView) findViewById(R.id.cloudread_title_name);
        viewPager = (HackyViewPager) findViewById(R.id.cloudread_vp);
        tvName = (TextView) findViewById(R.id.common_header_name);

        topLayout = findViewById(R.id.cloudread_top_layout);
        bottomLayout = findViewById(R.id.cloudread_bottom_layout);

        btn_sign_read = (Button) findViewById(R.id.btn_sign_read);
    }

    private void setListeners() {
        ivTitleBack.setOnClickListener(this);
        viewPager.setOnClickListener(this);
        btn_sign_read.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.cloudread_title_back) {
            finish();
        } else if (i == R.id.btn_sign_read) {
            if (mSignState) {
                new CustomDialog.Builder(this)
                        .setMessage("是否确认已阅读该公文")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                HttpClient.getInstance(CloudReadActivity.this).post(new IsReadDocumentFileReq(qryKnowledgeDocumentListEty.getDocumentId()), CloudReadActivity.this);
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create().show();
            }
        }
    }

    private TranslateAnimation mShowTopAnimation;
    private TranslateAnimation mHideTopAnimation;
    private TranslateAnimation mShowBottomAnimation;
    private TranslateAnimation mHideBottomAnimation;

    private void initAnimation() {
        // 从自已-1倍的位置(屏幕顶部)移到自己原来的位置
        mShowTopAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mHideTopAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
        mShowTopAnimation.setDuration(500);
        mHideTopAnimation.setDuration(500);

        // 从自已1倍的位置(屏幕底部)移到自己原来的位置
        mShowBottomAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mHideBottomAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
        mShowBottomAnimation.setDuration(500);
        mHideBottomAnimation.setDuration(500);
    }

    private void updateView() {
        showInfo = !showInfo;
        if (showInfo) {
            topLayout.startAnimation(mShowBottomAnimation);
            bottomLayout.startAnimation(mShowTopAnimation);
            topLayout.setVisibility(View.VISIBLE);
            bottomLayout.setVisibility(View.VISIBLE);
        } else {
            topLayout.startAnimation(mHideBottomAnimation);
            bottomLayout.startAnimation(mHideTopAnimation);
            topLayout.setVisibility(View.GONE);
            bottomLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onViewTap(View view, float x, float y) {
        updateView();
    }

    /**
     * 显示签读按钮
     *
     * @param arg0 当前页码
     */
    private void showSign(int arg0) {
        if ("y".equals(isDocumentFile) && arg0 == qryKnowledgeDocumentListEty.getPages()) {
            btn_sign_read.setVisibility(View.VISIBLE);
        } else {
            btn_sign_read.setVisibility(View.GONE);
        }
    }

}
